<?php

namespace App\Store\Controllers\Wxapp\WxappCoupon;


use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Wxapp\WxappCoupon;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Wxapp\WxappCouponCodeList;
use App\Store\Models\Wxapp\WxappSetting;
use App\Store\Services\Wxcoupon\Wxcoupon;
use App\Store\Validate\Wxapp\WxappCoupon\WxappCoupon as ValidateWxappWxappCoupon;
use Illuminate\Support\Facades\Log;

class WxappCouponController extends Controller
{
    public function getlist(Request $request)
    {
        $list = WxappCoupon::getList($request);
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        foreach($list['list'] as &$val){
            if($val['store_ids']==''){
                $val['store_listinfo']=SiteStore::where(['cp_id'=>$cp_id])->select(['id','store_name'])->get()->toArray();
            }else{
                if(is_numeric($val['store_ids']) && intval($val['store_ids'])>0){
                    $val['store_listinfo']=SiteStore::where(['id'=>intval($val['store_ids']),'cp_id'=>$cp_id])->select(['id','store_name'])->get()->toArray();
                }else{
                    $val['store_listinfo']=SiteStore::whereIn('id',explode(',',$val['store_ids']))->where(['cp_id'=>$cp_id])->select(['id','store_name'])->get()->toArray();
                }
            }
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }


    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = WxappCoupon::where([['id', $id],['cp_id',$cp_id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $info]);
    }

    /**
     *新增
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['store_ids','img_path', 'stock_name', 'goods_category_names', 'goods_name', 'stock_type', 'available_begin_time', 'available_end_time',
        'discount_amount', 'discount_percent', 'transaction_minimum','max_coupons_per_user','coupon_code_count','remark']);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $Validate = new ValidateWxappWxappCoupon();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        if($req_data['stock_type']=='NORMAL'){
            if(!isset($req_data['discount_amount']) || intval($req_data['discount_amount'])<=0){
                return response()->json(['code' => '001', 'msg' => '满减券，优惠金额不能为空或小于0']);
            }
        }else{
            $req_data['discount_amount']=0;
        }

        if($req_data['stock_type']=='DISCOUNT'){
            if(!isset($req_data['discount_percent']) || intval($req_data['discount_percent'])<=0 || intval($req_data['discount_percent'])>=100 ){
                return response()->json(['code' => '001', 'msg' => '折扣券，折扣比例不能为空或不符合要求']);
            }
        }else{
            
            $req_data['discount_percent']=0;
        }

        $data=$req_data;
        $data['available_begin_time']=strtotime($data['available_begin_time']);
        $data['available_end_time']=strtotime($data['available_end_time']);
        if($data['available_begin_time']<0 || $data['available_end_time']<$data['available_begin_time']){
            return response()->json(['code' => '001', 'msg' => '请选择合适的时间区间']);
        }
        $data['available_end_time']=strtotime(date('Y-m-d',$data['available_end_time']).' 23:59:59');


        if(($data['available_end_time']-$data['available_begin_time'])>31536000){
            return response()->json(['code' => '001', 'msg' => '时间跨度不能超过一年']);
        }


        $params=[
            'stock_name'=>$req_data['stock_name'],
            'goods_name'=>$req_data['goods_name'],
            'stock_type'=>$req_data['stock_type'],
            'coupon_use_rule'=>[
                'coupon_available_time'=>['available_begin_time'=>date('Y-m-d',$data['available_begin_time']).'T'.date('H:i:s',$data['available_begin_time']).'+08:00','available_end_time'=>date('Y-m-d',$data['available_end_time']).'T'.date('H:i:s',$data['available_end_time']).'+08:00'],
                'use_method'=>'OFF_LINE'
            ],
            'stock_send_rule'=>['max_coupons'=>intval($req_data['coupon_code_count']),'max_coupons_per_user'=>intval($req_data['max_coupons_per_user'])],
            'out_request_no'=>date('YmdHis').$cp_id.time().mt_rand(1000,9999),
            'coupon_code_mode'=>'MERCHANT_UPLOAD',
        ];




        if($req_data['stock_type']=='NORMAL'){
            $params['coupon_use_rule']['fixed_normal_coupon']=['discount_amount'=>intval($req_data['discount_amount']),'transaction_minimum'=>intval($req_data['transaction_minimum'])];
        }else{
            $params['coupon_use_rule']['discount_coupon']=['discount_percent'=>intval($req_data['discount_percent']),'transaction_minimum'=>intval($req_data['transaction_minimum'])];
        }

        // print_r($params);exit;
        //$goods_category_names=is_array($req_data['goods_category_names'])?$req_data['goods_category_names']:(is_array(json_decode($req_data['goods_category_names'],true))?json_decode($req_data['goods_category_names']):[]);
        $store_ids=is_array($req_data['store_ids'])?$req_data['store_ids']:(is_array(json_decode($req_data['store_ids'],true))?json_decode($req_data['store_ids']):[]);

        $setting=WxappSetting::where([['cp_id',$cp_id]])->first();
        if(!$setting){
            return response()->json(['code' => '001', 'msg' => '微信平台未配置']);
        }

        //$goods_category_ids=GoodsCategory::where(['cp_id'=>$cp_id])->whereIn('store_id',$store_ids)->whereIn('category_name',$goods_category_names)->pluck('id')->toArray();

        $Wxcoupon=new Wxcoupon($cp_id);
        $res=$Wxcoupon->createcoupon($params);
        Log::info($res);
        if($res['code']=='000'){
            $stock_id=$res['data']['stock_id'];
            $data['store_ids']=count($store_ids)>0?join(',',$store_ids):'';
            // $data['goods_category_names']=count($goods_category_names)>0?join(',',$goods_category_names):'';
            // $data['goods_category_ids']=count($goods_category_ids)>0?join(',',$goods_category_ids):'';
            $data['cp_id']=$cp_id;
            $data['out_request_no']=$params['out_request_no'];
            $data['create_at']=time();
            $data['update_at']=time();
            $data['remark']=isset($data['remark'])?$data['remark']:'';
            $data['stock_id']=$stock_id;

            WxappCoupon::create($data);

            return response()->json(['code' => '000', 'msg' => '创建成功']);
        }else{
            return response()->json(['code' => '001', 'msg' => $res['msg']]);
        }
    }

    public function getcouponcodelist(Request $request)
    {
        $coupon_id=intval($request->coupon_id);
        if($coupon_id<=0){
            return response()->json(['code' => '001', 'msg' => '无效错误']);
        }
        $list = WxappCouponCodeList::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 删除,已领取的可以使用
     */
    public function dodel(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = WxappCoupon::where([['id', $id],['cp_id',$cp_id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        WxappCoupon::where([['id', $id]])->update(['is_del' => 2, 'del_at' => time()]);

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }
}